package com.sesame.controller;

import kim.sesame.common.web.controller.AbstractWebController;
import kim.sesame.common.result.ApiResult;
import lombok.extern.apachecommons.CommonsLog;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

@CommonsLog
@RestController
@RequestMapping("/test")
public class TestController extends AbstractWebController {

    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/readDb")
    public ApiResult readDb(String id) {
        String key = "redis_key_test_" + id;
        String name = Thread.currentThread().getName();

        RLock lock = redissonClient.getLock(key);
        log.info(MessageFormat.format("{0}尝试获取锁,key : {1}", name, key));
        try {
            Long timeout = 10L;
            lock.lock();
            log.info(MessageFormat.format("{0}获取锁成功,key : {1}", name, key));
            TimeUnit.SECONDS.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            log.info(MessageFormat.format("{0} unlock success ,key : {1}", name, key));
        }
        return success();
    }
}
